﻿using System;
using System.Collections.Generic;
using System.Linq;
using TodoPro.System.Command;
using TodoPro.System.Event;
using TodoPro.System.Query;
using TodoPro.Utility;
using UnityEditor;
using UnityEngine;

namespace TodoPro.Editor
{
    public class TodoProAppWindow : EditorWindow
    {
        [MenuItem("TodoPro/Open Window %t")]
        public static void Open()
        {
            var window = GetWindow<TodoProAppWindow>();
            window.position = new Rect(300, 300, 320, 568);
            window.titleContent = new GUIContent("Todo Pro");
            window.Init();
            window.Show();
        }

        private List<Todo> mTodos;

        private TodoEventSystemNode mEventSystemNode;

        void Init()
        {
            mEventSystemNode = TodoEventSystemNode.Allocate();
            TodoProConfig.RegisterUtility<IStorage>(new EditorPrefsStorage());
            TodoProConfig.GetModel<ITodoModel>().Load();

            mTodos = new GetTodosByFilterQuery()
                .Do();

            mEventSystemNode.Register<OnTodoRemoveEvent>(@remove =>
            {
                mTodos = new GetTodosByFilterQuery()
                    .Do();
            });

            mEventSystemNode.Register<OnTodoAddEvent>(@remove =>
            {
                mTodos = new GetTodosByFilterQuery()
                    .Do();
            });
        }

        void OnDestroy()
        {
            mEventSystemNode.Recycle2Cache();
            mEventSystemNode = null;
            
            TodoProConfig.GetModel<ITodoModel>().Save();
            
        }

        private string mTodoContentInput;

        private void OnGUI()
        {
            GUILayout.BeginHorizontal("box");
            mTodoContentInput = EditorGUILayout.TextField(mTodoContentInput);

            if (GUILayout.Button("+"))
            {
                TodoProConfig.SendCommand(new AddTodoCommand(mTodoContentInput));
                
                mTodoContentInput = string.Empty;
            }

            GUILayout.EndHorizontal();

            mTodos.ForEach(RenderTodoItem);
        }

        void RenderTodoItem(Todo todo)
        {
            GUILayout.BeginHorizontal("box");
            GUILayout.Toggle(todo.Finished, todo.Content);
            
            if (GUILayout.Button("-", GUILayout.Width(20)))
            {
                TodoProConfig.SendCommand(new RemoveTodoCommand(todo.Id));
            }

            GUILayout.EndHorizontal();
        }
    }
}